package com.algorithm.learning.base.链表;

/**
 * @program: algorithm-learning
 * @description:
 * @author: YuKai Fan
 * @create: 2024/8/20 20:41
 **/
public class 双链表 {

    public static class DoubleNode {
        private int value;
        private DoubleNode last;
        public DoubleNode next;
        public DoubleNode(int value) {
            this.value = value;
        }
    }

    /**
     * 反转双链表
     * @param head
     * @return
     */
    public static DoubleNode reverseDoubleList(DoubleNode head) {
        DoubleNode pre = null;
        DoubleNode next = null;
        while (head != null) {
            // 记录下一个环境
            next = head.next;
            head.next = pre;
            head.last = next;
            pre = head;
            head = next;
        }
        return pre;
    }

    public static void main(String[] args) {
        DoubleNode doubleNode1 = new DoubleNode(1);
        DoubleNode doubleNode2 = new DoubleNode(2);
        DoubleNode doubleNode3 = new DoubleNode(3);

        doubleNode1.last = null;
        doubleNode1.next = doubleNode2;

        doubleNode2.last = doubleNode1;
        doubleNode2.next = doubleNode3;

        doubleNode3.last = doubleNode2;
        doubleNode3.next = null;

        DoubleNode doubleNode = reverseDoubleList(doubleNode1);
        while (doubleNode != null) {
            System.out.println(doubleNode.value);
            doubleNode = doubleNode.next;
        }
    }
}
